package cn.max.controllers;

import cn.incontent.cda.client.common.ArgumentList;
import cn.incontent.cda.client.utils.CDAUtils;
import cn.incontent.fastjson.JSONException;
import cn.incontent.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;


/**
 *@author Val.(Valentine Vincent) E-mail:valer@126.com
 *@version 1.0
 *@date 2013-12-8
 *Instruction : 
 **/
public abstract class ADService {

	private ModuleContext moduleContext;

	public ModuleContext getModuleContext() {
		return moduleContext;
	}
	
	protected String getTmpDir() {
		return System.getProperty("java.io.tmpdir");
	}

	@SuppressWarnings("unused")
	private void setModuleContext(ModuleContext moduleContext) {
		this.moduleContext = moduleContext;
	}
	
	public HttpServletRequest getRequest() {
		return moduleContext.getRequest();
	}

	public HttpServletResponse getResponse() {
		return moduleContext.getResponse();
	}
	
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	public ArgumentList getArgs() {
		return moduleContext.getArgs();
	}

	public List<FileItem> getFiles() {
		return moduleContext.getFiles();
	}

	public String getParam(String key) {
		return moduleContext.getParam(key);
	}
	
	public void out(Object obj) {
		if (obj instanceof Map) {
			obj = new org.json.simple.JSONObject((Map) obj);
		}

		outString(obj.toString());
	}
	
	private void outString(String str) {
		try {
			getResponse().setContentType("text/html; charset=utf-8");
			PrintWriter out = getResponse().getWriter();
			out.write(str);
		} catch (IOException e) {

		}
	}
	
	public JSONObject getMsg(boolean success, Object msg) {

		JSONObject json = new JSONObject();

		if (msg instanceof Exception) {
			String detail = CDAUtils.getStackTrace((Throwable) msg);

			try {
				json.put("errorLocation", "APP SERVVER");
				json.put("errorDetail", CDAUtils.stringToHtml(detail));
			} catch (JSONException e) {
				CDAUtils.printStackTrace(e);
			}

			String message = ((Exception) msg).getMessage();

			if (message == null) {
				message = "";
			}

			msg = message;
			if (message.length() > 50) {
				msg = message.substring(0, 50) + "...";
			}

		}

		try {
			json.put("success", success);
			if (msg != null) {
				json.put("msg", msg);
			}
		} catch (JSONException e) {
			CDAUtils.printStackTrace(e);
		}
		return json;

	}
	
}
